<template>
	<view>
		<u-upload :fileList="list" :accept="accept" @afterRead="afterRead" @delete="deletePic" name="1" multiple
			:maxCount="disabled?list.length:maxCount" :width="width" :height="height" :capture="['album', 'camera']"
			:uploadText="uploadText" :disabled="disabled" :deletable="!disabled">
		</u-upload>
	</view>
</template>

<script>
	// import OSS from "ali-oss"
	import Base64 from './Base64.js';
	import moment from 'moment'
	var CryptoJS = require('crypto-js');

	export default {
		name: "upload",
		props: {
			accept: {
				type: String,
				default: 'image',
			},
			maxCount: {
				type: Number,
				default: 1,
			},
			value: {
				type: String,
				default: '',
			},
			width: {
				type: String,
				default: '155rpx',
			},
			height: {
				type: String,
				default: '155rpx',
			},
			uploadText: {
				type: String,
				default: '上传',
			},
			disabled: {
				type: Boolean,
				default: false,
			},
		},
		data() {
			return {
				website: this.$store.state.website,
				fileList: [],
				client: null,
				ossInfo: {}
			};
		},
		computed: {
			list() {
				let list = []
				for (let vo of this.fileList) {
					list.push({
						status: vo.status,
						message: vo.status,
						url: vo.status == 'success' ? (vo.url) : vo.url,
						fileId: vo.fileId
					})
				}
				return list
			}
		},
		watch: {
			value() {

				this.initFileList()
			}
		},
		mounted() {
			this.$http.post('/data/api.data/oss', {}).then((res) => {
				this.ossInfo = res.data
			})
			this.initFileList()

		},
		methods: {
			initFileList() {
				let arr = []
				if (this.value) {
					arr = this.value.split('|')
				}
				console.log(arr, 1111)
				let fileList = []
				for (let i in arr) {
					fileList.push({
						status: 'success',
						message: '',
						url: arr[i],
						fileId: i
					})
				}
				this.fileList = fileList
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				console.log(event)
				let fileListLen = this.fileList.length
				lists.map((item) => {
					this.fileList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const url = await this.uploadF(lists[i].url, i)
					// let result = JSON.parse(res)
					console.log(url, 'result')
					let item = this.fileList[fileListLen]
					this.fileList.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: url,
						fileId: url
					}))
					fileListLen++
				}
				this.emitValue()
			},
			getPolicy() {
				let date = new Date();
				date.setHours(date.getHours() + 87600);
				let expire = date.toISOString();
				const policy = {
					"expiration": expire, // 设置该Policy的失效时间
					"conditions": [
						["content-length-range", 0, 3 * 1024 * 1024] // 设置上传文件的大小限制
					]
				};
				return Base64.encode(JSON.stringify(policy));
			},

			uploadF(url, i) {
				return new Promise((resolve, reject) => {
					const fileExtension = url.split('.').pop()
					const filePath = 'sbbxgl_oshainiu_cn/' + moment().unix() + '-' + i + '.' + fileExtension
					const uploadUrl = this.ossInfo.type + "://" + this.ossInfo.host;



					const accessKeyId = this.ossInfo.accessKey;


					const policy = this.getPolicy();
					var accessKeySecret = this.ossInfo.secretKey; // 替换为你的 AccessKeySecret
					var signature = CryptoJS.HmacSHA1(policy, accessKeySecret).toString(CryptoJS.enc.Base64);

					console.log(uploadUrl, 'signature', url)
					uni.uploadFile({
						url: uploadUrl,
						filePath: url,
						name: 'file',
						formData: {
							'key': filePath, // 服务利用key找到文件
							'policy': policy,
							'OSSAccessKeyId': accessKeyId,
							'signature': signature,
							'success_action_status': '200',
						},
						success: function(res) {
							resolve(uploadUrl + "/" + filePath)
						},
						fail: function(err) {
							console.log(err)

						},
					})

				})

			},
			// 删除图片
			deletePic(event) {
				this.fileList.splice(event.index, 1)
				this.emitValue()
			},
			emitValue() {
				let arr = []
				for (let vo of this.fileList) {
					arr.push(vo.url)
				}
				this.$emit('input', arr.join('|'))
			}
		}
	}
</script>

<style scoped lang="scss">
	::v-deep .u-upload {
		width: 182rpx;
		height: 182rpx;
		background: rgba(255, 255, 255, 1);
		border: 2rpx solid #DDDDDD;
		opacity: 1;
		border-radius: 10rpx;

		.u-icon__icon {
			color: rgba(153, 153, 153, 1);
		}
	}
</style>